import singleton from "@/util/singleton.js"
import {
	userStore
} from "@/store/index.js"
const store = userStore()
const url = "ws://ai.qinhai269.com:7272"
// const url = "ws://0.0.0.0:7272"
class Push {
	constructor() {
		this.me_close = false;
		this.socketTask;
		this.deviceId = "";
		this.status = false;

		// 监听连接关闭close
		uni.onSocketClose((e) => {
			this.socketTask = null;
			if (!this.me_close) { //判断是否主动关闭进行重新连接
				setTimeout(_ => {
					this.#connect()
				}, 5000)
			}
		})

		uni.onSocketError((err) => {
			console.log('连接失败，请检查');
			this.socketTask = null;
			if (!this.me_close) { //判断是否主动关闭进行重新连接
				setTimeout(_ => {
					this.#connect()
				}, 2000)
			}
		})

		uni.onSocketOpen((res) => {
			console.log('连接成功！');
			this.status = true;
		});

		uni.onSocketMessage(function(res) {
			let data = JSON.parse(res.data)
			if (data.type != "ping") {
				uni.$emit('message', data);
				if (data.type == 'updateUser') {
					store.setInfo(data.data)
				}
				if(data.status == 402) {
					store.logout();
					// location.reload()
				}
			}
		});
	}

	start() {
		this.#connect()
	}


	#connect() {
		if (this.status) {
			return false;
		}
		if (this.socketTask) {
			uni.closeSocket()
			this.socketTask = null;
			return false;
		}
		this.socketTask = uni.connectSocket({
			url: `${url}?token=${store.info.token || ''}`,
		});
	}

	reconnect() {
		uni.closeSocket()
		this.socketTask = null;
		this.#connect()
	}

	stop() {
		this.me_close = true
		uni.closeSocket({
			success() {
				// 确保已经关闭
				this.socketTask = null;
			}
		})
	}

	send(content, type = 'search') {
		let _this = this;
		uni.sendSocketMessage({
			data: JSON.stringify({
				device_id: store.deviceId,
				token: store.info.token,
				type,
				content
			}),
			success() {},
			fail(err) {
				console.log("失败", err);

			},
		});
	}

	watch(callback) {
		uni.onSocketMessage(function(res) {
			let data = JSON.parse(res.data)
			if (data.type != "ping") {
				if (typeof callback === 'function') {
					callback(data)
				}
			}
		});
	}
}
export default singleton(Push)